package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @param: []
     * @return: java.util.List<com.hmdp.entity.ShopType>
     * @description: 查询店铺类型，设置缓存
     **/
    @Override
    public List<ShopType> queryTypeList() {
        //        List<ShopType> typeList = typeService.query().orderByAsc("sort").list();

        String key = RedisConstants.CACHE_SHOP_TYPE_LIST_KEY;
        List<String> strList = stringRedisTemplate.opsForList().range(key, 0, -1);
        List<ShopType> shopTypeList = new ArrayList<>();
        if (strList != null && strList.size() != 0) {
            log.info("###### redis中存在ShopType");
            for (String s : strList) {
                shopTypeList.add(JSONUtil.toBean(s, ShopType.class));
            }
            return shopTypeList;
        }

        log.info("###### redis中不存在ShopType,到数据库查询");
        shopTypeList = query().orderByAsc("sort").list();
        strList = new ArrayList<>();
        for (ShopType shopType : shopTypeList) {
            strList.add(JSONUtil.toJsonStr(shopType));
        }
        // 存入redis时添加有效时间
        stringRedisTemplate.opsForList().leftPushAll(key, strList);
        stringRedisTemplate.expire(key, RedisConstants.CACHE_SHOP_TYPE_LIST_TTL, TimeUnit.MINUTES);
        return shopTypeList;
    }
}
